<?php
class RoleController extends CommonController{
	/**
	 * 角色保存
	 */
	public function save(){
	    if($this->isGet()){
	    	$menuList=require CONFIG_PATH.'/config.menu.php';
	    	$this->assign('menuList',$menuList);
            $this->display();
	    }else{
            $db=M(CONTROLLER_NAME);
            $data['name']=$_POST['name'];
            $data['remark']=$_POST['remark'];
           	begin();
            $role_id=$db->save($data);
            $role_menu_result=true;
            if(!empty($_POST['menu_id'])){
            	$role_menu=array();
	            foreach($_POST['menu_id'] as $i=>$vo){
	            	$role_menu[$i]['role_id']=$role_id;
	                $role_menu[$i]['menu_id']=$vo;
	            }
	            $role_menu_result=M('RoleMenu')->save($role_menu);
            }
            if($role_id&&$role_menu_result){
            	commit();
                $this->redirect('index');
            }else{
            	rollback();
                $this->error('添加角色失败,请联系管理员');
            }
	    }
	}
	public function updateBefore(){
	    if($this->isGet()){
	        $roleMenuList=M('RoleMenu')->field('menu_id',true)->where('role_id='.intval($_GET['id']))->select();
	        $this->assign('roleMenuList',$roleMenuList);
	        $menuList=require CONFIG_PATH.'/config.menu.php';
	        $this->assign('menuList',$menuList);
	    }else{
	    	$id=intval($_POST['id']);
	    	$db=M('RoleMenu');
	        $db->delete(array('role_id'=>$id));
	        empty($_POST['menu_id']) and $_POST['menu_id']=array();
	        $db->begin();
	        foreach($_POST['menu_id'] as $v){
	        	$roleMenu['role_id']=$id;
	        	$roleMenu['menu_id']=$v;
	        	$result=$db->save($roleMenu);
                if(!$result){
                    $db->rollback();
                    $this->error('添加失败,请联系管理员');
                }
	        }
	        $db->commit();
	    }
	}
}